// tslint:disable
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Router } from "@angular/router";

import { AlertController } from "@ionic/angular";

import { EventService } from "src/app/shared/service/event.service";

import { AppGlobalService } from "./app-global.service";
// import { TabsService } from './tabs.service';
declare var showLoading;
declare var completeLoading;
declare var showAlert;
@Injectable({ providedIn: "root", })

export class HttpService {

  // 测试
  // bathUrl = 'http://192.168.1.212:8987/'; // 测试环境api接口路径
  // wsServiceAPI = "ws://talk.xwkj.local/talk/talkServer/"; // 测试ws地址 // 192.168.1.187:3088
  // talkQueryFriendsList = "http://talk.xwkj.local/talk/api/queryFriends"; // 测试环境好友列表接口
  // talkQueryHistoriesList = "http://talk.xwkj.local/talk/api/queryHistories"; // 测试环境好友聊天历史记录列表接口

  // 线上
  bathUrl = "https://app-api.xw18.cn/";  // 线上环境api接口路径
  wsServiceAPI = "wss://talk-service.xw18.cn:443/talk/talkServer/";// 线上ws地址
  talkQueryFriendsList = "https://talk-service.xw18.cn/talk/api/queryFriends"; // 线上邀约列表接口
  talkQueryHistoriesList = "https://talk-service.xw18.cn/talk/api/queryHistories"; // 测试环境好友聊天历史记录列表接口

  // 开发 、 性能
  // bathUrl = 'http://zeno-performance-gateway.xwkj.local/openapi/';  // 性能环境api接口路径
  // bathUrl = 'http://zeno-dev-gateway.xwkj.local/openapi/'; // 开发环境

  kd100API = "https://tools.xw18.cn";// 快递100
  baiduAPI = "https://tools2.xw18.cn";// 百度定位API

  headers: any;
  isLoading = false;
  retry = 0;
  private timer: any
  constructor(
    // private toast: ToastService,
    public http: HttpClient,
    public eventService: EventService,
    private appGlobalService: AppGlobalService,
    private alertController: AlertController,
    private router: Router

  ) { }


  specialUrlPost(
    path: string,
    params: any,
    callback: Function,
    err?: Function
  ) {

    this.headers = new HttpHeaders({
      "Content-Type": "application/json;charset=UTF-8",
      token: "4403",
    });
    const url = this.bathUrl + path;
    return this.http.post(url, params, { headers: this.headers }).subscribe(
      (data) => {
        // this.hideLoading();
        callback(data);
      },
      (error) => {
        // this.hideLoading();
        this.handleError(error, path, params);
        if (err) {
          err(error.error, path, params);
        }
      }
    );
  }

  setHeasers() {
    this.headers = new HttpHeaders({
      "Content-Type": "application/json;charset=UTF-8",
    });
  }


  // http://192.168.1.200:8008/index.php?title=%E5%85%83%E6%95%B0%E6%8D%AE%E9%94%99%E8%AF%AF%E4%BB%A3%E7%A0%81%E5%88%97%E8%A1%A8#.E9.94.99.E8.AF.AF.E4.BB.A3.E7.A0.81
  // 系统错误代码
  // 1000 系统异常
  // 1001 参数错误
  // 1002 token无效
  // 1003 没有权限
  // 1004 数据版本升级
  // 1005 业务限制
  // 1006 未找到该数据

  // 5500 新增失败
  // 5501 类型转换失败
  // 5502 session无效
  // 5503 生成应用脚本编译失败
  // 5504 错误类型无法实例化
  // 5505 类型解释错误
  // 5506 数据异常
  // 5507 脚本类实例化不合法
  // 5508 参数缺少
  // 5509 数据源为空
  // 5510 脚本执行错误
  // 5511 变量不存在或值为空
  // 5512 脚本执行终止
  // 5513 表达式错误
  // 5514 数组越界
  // 5515 其它错误
  // 5516 Session挤出下线
  handleError(error, path?, params?) {
    if (error.error && error.error.code == "5502") {
      if (path !== "application/home/") {
        this.getSession(
          (session) => {
            this.appGlobalService.closeAlertAndPopoverAndModalAndMenu();
            if(localStorage.getItem("ALP") && localStorage.getItem("loginAccount")){
              this.post('application/execEvent',{ 
                "sessionId":session , 
                "params":{"account":localStorage.getItem("loginAccount"),
                "password":localStorage.getItem("ALP")}
              },(res)=>{
                localStorage.setItem("loginStatus", "true");
                this.appGlobalService.loginStatus = true;
                this.reloadCurrentPage(200);

              },(err)=>{
                this.reloadCurrentPage(200);
              })
            } else {
              this.reloadCurrentPage(200);
            }

            
          },
          (err) => { }
        );
      }
    } else {
      console.log("error----other->" + JSON.stringify(error));
      console.log("error----path->" + JSON.stringify(path));
      console.log("error----params->" + JSON.stringify(params));
      // 如不是page
      // if (!params.pageId) {
      //     this.checkBack();
      // }
      // this.checkBack();
    }
  }
  readyParamsForShellData(path, params) {
    if (params && params.params) {
      const p = JSON.parse(JSON.stringify(params));
      p.params["isShell"] = true;
      if (params.params.forNgTabs == "true") {
        this.postForShellData(path, p, true);
      } else {
        this.postForShellData(path, p);
      }
    }

  }
  postForShellData(path, params, forNgTabs?) {
    params.cancelLoading = true; // 二次数据不loading
    this.post(path, params, res => {
      console.log("isShell res :" + res)
      if (res["script"]) {
        this.appGlobalService.toShellData(JSON.parse(res["script"]), forNgTabs,params);
      }
    })
  }
  post(
    path: string,
    params: any,
    callback: Function,
    err?: Function,
    isUsePath?
  ) {
    let url = isUsePath ? path : this.bathUrl + path;
    this.setHeasers();
    if ((params.pageId || params.viewId) && params.tagOrder === undefined) {
      this.delayShowLoading();
    }
    if (params.cancelLoading !== undefined) {
      this.isLoading = false;
    }
    // page or part use  https://app-api.xw18.cn  for  on line
    if (url.indexOf('submit') <= -1 && url.indexOf('xw18.cn') > -1) {
      url = isUsePath ? path : 'https://app-api.xw18.cn/' + path;
    }
    if (url.indexOf('submit') > -1){ // 2024.11.15 for fengwosh register log
      if (params && params.content 
        && localStorage.getItem('client')){
        params.content['client'] = localStorage.getItem('client');
      }
    }

    if (localStorage.getItem('ShareH5')) {

      // Object.assign(params,  JSON.parse(localStorage.getItem('ShareH5')));
      const h5p = JSON.parse(localStorage.getItem('ShareH5'));
      if (params.params && params.params.base_info_id && h5p.base_info_id) {
        params.params.base_info_id = h5p.base_info_id;
      }
    }

    // 2.2.2 新增字段 fromH5forRecord用于标识从H5进入
    if (this.appGlobalService.fromH5forRecord
      && params.content
      && params.content['needBaseInfoId'] !== undefined) {
      params.content['base_info_id'] = this.appGlobalService.fromH5forRecord;
    }
    let cacheObj: any;
    if (params.pageId || params.viewId) {
      if (params.params && params.params.isShell) {

        return this.postData(cacheObj, path, url, params, { headers: this.headers }, callback, err);

      } else {
        //? params = JSON.parse(JSON.stringify(params)); 2023.11.17 会改变indexTab = undefined
        this.appGlobalService.getCacheByKey(params.pageId || params.viewId, (res) => {

          if (res !== "-1") {
            cacheObj = res;
            console.log('data_hash_key is :', res.data_hash_key);
            params.params['data_hash_key'] = res.data_hash_key;
            // use cache & cancel loading
            this.isLoading = false;
            console.log('use shell cache & cancel loading!!!');
            callback(cacheObj.data);
          } else {
            params.params['data_hash_key'] = "new";
          }
          return this.postData(cacheObj, path, url, params, { headers: this.headers }, callback, err);
        });
      }

    } else {
      return this.postData(cacheObj, path, url, params, { headers: this.headers }, callback, err);
    }

  }

  postData(cacheObj: any, path: string, url: string, params: any, header: any, callback: Function, err?: Function) {
    // 以localStorage.getItem('sessionId')为准 请求新的session之前先删除旧的，确保能取到的是最新的sessionid
    if (params.sessionId && params.sessionId !== localStorage.getItem('sessionId')) {
      console.error('post sessionId 与 localStorage id 不一致！！！')
      console.error('更新为localStorage sessionId:' + localStorage.getItem('sessionId'))
      params.sessionId = localStorage.getItem('sessionId');
    }
    this.http.post(url, params, header).subscribe(
      async (data) => {
        this.hideLoading();


        if (data['code'] == '5502' || data['message'] === '退出成功') {
          if (data['message'] !== '退出成功') {
            data['message'] = null; // session过期时不提示。
          }
          callback(data);
          if (path !== "application/home/") {

            this.getSession(
              (session) => {

                this.appGlobalService.closeAlertAndPopoverAndModalAndMenu();
                if(localStorage.getItem("ALP") && localStorage.getItem("loginAccount") && data['message'] !== '退出成功'){
                  this.post('application/execEvent',{ 
                    "sessionId":session , 
                    "params":{"account":localStorage.getItem("loginAccount"),
                    "password":localStorage.getItem("ALP")}
                  },(res)=>{
                    localStorage.setItem("loginStatus", "true");
                    this.appGlobalService.loginStatus = true;
                    this.reloadCurrentPage(200);
    
                  },(err)=>{
                    this.reloadCurrentPage(1000);
                  })
                } else {
                  this.reloadCurrentPage(1000);
                }
                
              },
              (err) => { }
            );
          }
        } else
          if (data["script"] && JSON.parse(data["script"]).code === 5516) {
            // this.appGlobalService.goBack();
            // this.eventService.eventEmit.emit('reloadCurrentPage', '502');
            // this.router.navigate([''], { queryParams: {} });
            localStorage.removeItem('ALP');
            localStorage.removeItem('loginStatus');
            this.appGlobalService.loginStatus = false;
            localStorage.removeItem("WebSocketSID");
            // A手机登录账号，B手机再登录同一账号挤下来后，A手机点击商机详情的在线聊 进去了聊天页面。
            // 2023.11.24 退出登录，不删除logginAccount localStorage.removeItem('loginAccount'); // fixed by andrew.wen for bug-view-4359.html
            localStorage.removeItem("isDetailPage");
            localStorage.removeItem("invitationArr");
            localStorage.removeItem("inMsgNum");
            localStorage.removeItem("isEnterDetailChatPage");
            localStorage.removeItem("chatPageFrom");
            localStorage.removeItem("shareOppDetail");
            localStorage.removeItem("needRemberResult");
            localStorage.removeItem("refreshbtNavDefaultTabForPxwTag");
            localStorage.removeItem('backToNewShop');
            localStorage.removeItem("titleBarBackCount");
            localStorage.setItem("needRefreshTab1", "true");
            localStorage.setItem("needRefreshTab2", "true");
            localStorage.setItem("needRefreshTab3", "true");
            localStorage.setItem("needRefreshTab4", "true");
            localStorage.setItem("needRefreshTab5", "true");
            const alert = await this.alertController.create({
              header: "",
              subHeader: "提示",
              backdropDismiss: false,

              message: JSON.parse(data["script"]).message,
              buttons: [
                {
                  text: "确定",
                  handler: () => {
                    if (data["script"] && JSON.parse(data["script"]).link) {
                      let link = JSON.parse(data["script"]).link;
                      if(!link.type){
                        link['type'] = "page";
                      }
                      if(!link.params){
                        link['params'] = {};
                      }
                      
                      this.eventService.eventEmit.emit('openPage', JSON.stringify(link))
                    }


                  },
                },
              ],
            });
            await alert.present();
          } else if (data["script"] && JSON.parse(data["script"]).data_hash_key && JSON.parse(data["script"]).data_hash_key === "1" && cacheObj && cacheObj.data) {
            console.log(' data_hash_key is 1 ');
            // 直接使用缓存模板立即 模板没有变化 二次请求数据
            this.readyParamsForShellData(path, params);

            // // use cache
            // callback(cacheObj.data);
          }
          else if (data["script"] && JSON.parse(data["script"]).isShell === true) {
            // isShell 需要二次请求数据
            params['data_hash_key'] = JSON.parse(data["script"]).data_hash_key; //
            this.readyParamsForShellData(path, params);

            if (JSON.parse(data["script"]).data_hash_key && JSON.parse(data["script"]).data_hash_key !== '-1') {
              const pageData = JSON.parse(data["script"]); //2024.10.08 清空模版数据中的购物车
              if (pageData.titleBar && pageData.titleBar.cart && pageData.titleBar.cart.count != undefined) {
                pageData.titleBar.cart.count = 0;
                data['script'] = JSON.stringify(pageData);
                // this.appGlobalService.consoleLog('pageData=','update data["script"] success!!!');
              }

              if (cacheObj && cacheObj.data) {
                console.log(' data_hash_key != -1 | put cache');
                // put cache
                this.appGlobalService.putCacheCallback({
                  id: params.pageId || params.viewId,
                  data: data,
                  data_hash_key: JSON.parse(data["script"]).data_hash_key
                }, (res) => { });
              } else {
                console.log(' data_hash_key != -1 | add cache');
                // add cache
                this.appGlobalService.addCacheCallback({
                  id: params.pageId || params.viewId,
                  data: data,
                  data_hash_key: JSON.parse(data["script"]).data_hash_key
                }, (res) => { });
              }

            }
            callback(data);
          } else {
            console.log(' isShell !== true |refreshCache !');
            if (data["refreshCache"] && data["refreshCache"] === true) {
              if (localStorage.getItem("topTapPartParams1")) {
                const topTapPartParams1 = JSON.parse(
                  localStorage.getItem("topTapPartParams1")
                );
                const topTapPartParams2 = JSON.parse(
                  localStorage.getItem("topTapPartParams2")
                );
                this.post(
                  "application/part",
                  topTapPartParams1,
                  async (res: any) => {
                    if (res) {
                      localStorage.setItem("topTapPart1", res.script);
                      console.log("msg----->tab1更新缓存...ok");
                      // document.getElementById('homeNavTab1').click();
                      this.eventService.eventEmit.emit("topTapPart1", "1");
                    }
                  }
                );
                this.post(
                  "application/part",
                  topTapPartParams2,
                  async (res: any) => {
                    if (res) {
                      localStorage.setItem("topTapPart2", res.script);
                      // document.getElementById('homeNavTab2').click();
                      this.eventService.eventEmit.emit("topTapPart2", "1");
                      console.log("msg----->tab2更新缓存...ok");
                    }
                  }
                );
              }
            }
            callback(data);
          }
      },
      (error) => {
        this.hideLoading();
        if (localStorage.getItem('netState') === 'No network connection') {
          this.alertNotNet()
        }
        if (!error.error.text) {

          this.handleError(error, path, params);
          if (err) {
            err(error.error, path, params);
          }
        } else {
          // 蜂喔赚钱宝 1.7.1需求 走事件直接返回值
          if (url.includes('execEvent')) {
            callback(error.error.text);
          }
        }
      }
    );
  }

  async alertNotNet() {
    if (localStorage.getItem('alertNotNetWork')) {
      return;
    }
    showAlert()
  }
  img_post(path: string, params: any, callback: Function, err?: Function) {
    let url;
    if (path.indexOf("http") > -1) {
      url = path;
    } else {
      url = this.bathUrl + path;
    }

    return this.http.post(url, params).subscribe(
      (data) => {
        callback(data);
      },
      (error) => {
        if (localStorage.getItem('netState') === 'No network connection') {
          this.alertNotNet()
        }
        this.handleError(error, path, params);
        if (err) {
          err(error.error, path, params);
        }
      }
    );
  }


  get(path: string, callback: Function, err?: Function, bath?: string) {
    // 如是home 或者 session 加loadding
    if (
      path.indexOf("application/openApp/") > -1 ||
      path.indexOf("application/debug/") > -1 ||
      path.indexOf("application/home/") > -1 ||
      path.indexOf("/wx/getAccessToken") > -1
    ) {
      this.delayShowLoading();
    }

    let url = bath ? path : this.bathUrl + path;
    // this.showLoading('');
    this.setHeasers();
    // private http: HttpClient,
    if (url.indexOf('xw18.cn') > -1) {
      url = bath ? path : 'https://app-api.xw18.cn/' + path;
    }
    return this.http.get(url, { headers: this.headers }).subscribe(
      (data) => {
        this.hideLoading();
        callback(data);
      },
      (error) => {
        this.hideLoading();
        if (localStorage.getItem('netState') === 'No network connection') {
          this.alertNotNet()
        }

        if (err) {
          if (path !== "message/userinfo/im/") {
            this.handleError(error, path);
          }
          err(error);
        }
      }
    );
  }

  // getLocationAddress(latitude: any, longitude: any, callback: Function, err?: Function) {
  //     
  // const url = this.baiduAPIUrl
  // + 'ak=sIq3pmhG5n4xVuKQ8eKr1BiV0hsLP2ek&renderReverse&location=' + latitude + ',' + longitude + '&output=json&pois=1';
  //     this.setHeasers();
  //     return this.http.get(url, { headers: this.headers })
  //         .subscribe((data) => {
  //             callback(data);
  //         }, (error) => {
  //             if (err) {
  //                 this.handleError(error);
  //                 err(error);
  //             }
  //         });
  // }


  delete(path: string, params: any, callback: Function, err?: Function) {
    const url = this.bathUrl + path;
    this.setHeasers();
    // this.showLoading();
    return this.http.delete(url, { params, headers: this.headers }).subscribe(
      (data) => {
        // this.hideLoading();
        callback(data);
      },
      (error) => {
        // this.hideLoading();
        if (err) {
          this.handleError(error, path, params);
          err(error.error, path, params);
        }
      }
    );
  }


  put(path: string, params: any, callback: Function, err?: Function) {
    const url = this.bathUrl + path;
    // this.showLoading('');
    this.setHeasers();
    return this.http.put(url, params, { headers: this.headers }).subscribe(
      (data) => {
        // this.hideLoading();
        callback(data);
      },
      (error) => {
        // this.hideLoading();
        if (err) {
          this.handleError(error, path, params);
          err(error.error, path, params);
        }
      }
    );
  }


  getSession(callback: Function, error: Function) {



    clearTimeout(this.timer);
    this.timer = setTimeout(() => {

      // 多个接口接连返回5502时 避免不要的多次请求sessionid
      if (localStorage.getItem("reGetSession") === "true") {
        callback(localStorage.getItem("sessionId"))
        setTimeout(() => {
          localStorage.removeItem("reGetSession")
        }, 5000);

      } else {

        localStorage.removeItem("sessionId");
        localStorage.removeItem('loginStatus');
        this.appGlobalService.loginStatus = false;
        localStorage.removeItem("WebSocketSID");
        // 2023.11.24 退出登录，不删除logginAccount localStorage.removeItem('loginAccount');
        localStorage.removeItem("isDetailPage");
        localStorage.removeItem("invitationArr");
        localStorage.removeItem("inMsgNum");
        localStorage.removeItem("isEnterDetailChatPage");
        localStorage.removeItem("chatPageFrom");
        localStorage.removeItem("shareOppDetail");
        localStorage.removeItem("needRemberResult");
        localStorage.removeItem("refreshbtNavDefaultTabForPxwTag");
        localStorage.removeItem('backToNewShop');
        localStorage.removeItem("titleBarBackCount");

        if (this.bathUrl.indexOf("https") > -1) {
          this.appGlobalService.getSessionPath =
            "application/openApp/xw/" + this.appGlobalService.ReleaseVersionCode;
        }
        if (this.appGlobalService.getSessionPath ===
          "application/openApp/xw/" + this.appGlobalService.ReleaseVersionCode) {

          this.get('application/openApp/xw/' + this.appGlobalService.ReleaseVersionCode, (ress) => {
            localStorage.setItem("sessionId", ress.sessionId);
            console.log("new session-------->\n", ress.sessionId);
            callback(ress.sessionId);
            // 5s 之内不请求新session
            localStorage.setItem("reGetSession", "true");
            setTimeout(() => {
              localStorage.removeItem("reGetSession");
            }, 5000);
          },
            (err) => {
              error(err);
            }
          );
        } else {
          if (this.appGlobalService.isPreview) {
            alert("预览项目不刷新sessionId，请清除浏览器缓存");

          } else if (this.appGlobalService.debugAppId > 0) {
            this.get(
              "application/debug/" + this.appGlobalService.debugAppId,
              (ress) => {
                localStorage.setItem("sessionId", ress.sessionId);
                console.log("new session-------->\n", ress.sessionId);
                callback(ress.sessionId);
                localStorage.setItem("reGetSession", "true");
                setTimeout(() => {
                  localStorage.removeItem("reGetSession");
                }, 5000);
              },
              (err) => {
                error(err);
              }
            );
          }
        }
      }

    }, 100);
  }

  reloadCurrentPage(milliSecond?) {
    if (milliSecond !== undefined) {
      setTimeout(() => {
        this.eventService.eventEmit.emit("reloadCurrentPage", "reloadCurrentPage");
      }, Number(milliSecond));
    } else {
      setTimeout(() => {
        this.eventService.eventEmit.emit("reloadCurrentPage", "reloadCurrentPage");
      }, 2000);
    }
  }

  async checkBack() {
    const that = this;
    // this.hideLoading();
    const alert = await this.alertController.create({
      header: "",
      subHeader: "提示",
      message: "服务器繁忙，请重新进入页面",
      buttons: [
        {
          text: "确定",
          handler: () => {
            console.log("确定，请重新进入页面!!!");
            that.eventService.eventEmit.emit("backLastPage", "backLastPage");
          },
        },
      ],
    });
    await alert.present();
  }

  delayShowLoading() {
    this.isLoading = true;
    setTimeout(() => {
      if (this.isLoading) {
        showLoading();
      }
    }, 250);
  }

  hideLoading() {
    this.isLoading = false;
    setTimeout(() => {
      completeLoading();
    }, 1);
  }
  gotoChat(itemObj, customerUserId?) {
    try {
      const that = this;
      const cityId = JSON.parse(localStorage.getItem("position"))
        ? JSON.parse(localStorage.getItem("position")).code
        : this.appGlobalService.defaultCityId;
      if (localStorage.getItem("userId")) {
        let tempUserId = '';
        if (itemObj && itemObj.link.params && itemObj.link.params.chatId) {
          tempUserId = itemObj.link.params.chatId;
        } else if (customerUserId !== undefined) {
          tempUserId = customerUserId;
        }
        this.getImId(
          itemObj.link.params.opportunity_id,
          itemObj.link.params.customer_id,
          cityId,
          (resItem) => {
            if (resItem.toId !== localStorage.getItem("userId")) {
              if (itemObj.submit) {
                resItem.submit = itemObj.submit;
              }
              if (itemObj.nickname) {
                resItem.nickname = itemObj.nickname;
              }
              let hiddenAddBtn = 'false';
              if (itemObj.link.params && itemObj.link.params.hiddenAddBtn !== undefined) {
                hiddenAddBtn = itemObj.link.params.hiddenAddBtn;
              }
              // 接收方手机号码 1.6.34新增
              if (customerUserId !== undefined) {
                localStorage.setItem('enterChatRoomByUserId', '1');
                that.eventService.eventEmit.emit('enterChatRoomByUserId',
                  { userId: customerUserId, fromFriendList: true });
              } else {
                localStorage.setItem('enterChatRoomByUserId', '1');
                that.eventService.eventEmit.emit('enterChatRoomByUserId',
                  { userId: resItem.toId, fromFriendList: true });
              }
            } else {
              console.log('发送方和接收方一致');
            }
          }
          , tempUserId);
      }
    } catch (error) {
      console.log("error----->" + JSON.stringify(error));
    }
  }


  // 邀约聊天新增接口 inviteChat
  async inviteChat(msg: string, myOpportunityId: string, userId: string, opportunityId: string, callFunction) {
    try {
      const params = {
        msg,
        myOpportunityId,
        userId, opportunityId
      };

      this.post("message/inviteChat", params, res => {

      }, err => {

      });
    } catch (error) {
      console.log("error----->" + JSON.stringify(error));
    }
  }
  getImId(
    opportunityId: string,
    customerId: string,
    cityId: string,
    callback: Function,
    customUserId?: string
  ) {
    const item = {
      datetime: new Date().getHours() + ":" + new Date().getMinutes(),
      id: "",
      type: "ppw",
      toId: "",
    };
    // 有userId
    if (customUserId) {
      item.toId = customUserId;
      item.id = customUserId + '-' + localStorage.getItem("userId");
      callback(item);
      return;
    }
    // 有商机id 
    if (opportunityId) {

      this.get(
        "message/chat/" + localStorage.getItem("userId") + "/" + opportunityId,
        (response) => {
          const data = response;
          if (data.status !== "success" || data.user_id === null) {
            // 取城市客服userId
            this.get(
              "message/service/" +
              localStorage.getItem("userId") +
              "/" +
              cityId,
              (chatCityRes) => {
                const serviceData = chatCityRes;
                if (serviceData.status === "success") {
                  item.toId = serviceData.service_id;
                  item.id =
                    serviceData.service_id +
                    "-" +
                    localStorage.getItem("userId"); // 2023.12.02 修复跳转聊天页面异常
                  callback(item);
                } else {
                  this.appGlobalService.showToast(
                    serviceData.msg,
                    3000,
                    "middle"
                  );
                  return;
                }
              }
            );
            // }
          } else {
            item.toId = data.user_id;
            item.id = data.user_id + "-" + localStorage.getItem("userId");
            callback(item);
          }
        },
        (error) => {
          console.log("msg-----> error:" + JSON.stringify(error));
        }
      );
    } else if (customerId) {
      // 铺小旺app 直接处理客户id
      item.type = "pxw";
      this.get("message/customer/" + customerId, async (customerResp) => {
        if (customerResp.status !== "success") {
          this.appGlobalService.showToast(customerResp["msg"], 3000, "middle");
          return;
        } else {
          item.toId = customerResp.user_id;
          item.id = customerResp.user_id + "-" + localStorage.getItem("userId");
          callback(item);
        }
      });
    }
  }



  async getImIdForInviteMsg(
    msg: any,
    opportunityId: string,
    myOpportunityId: string,

    callback: Function
  ) {
    const item = {
      datetime: new Date().getHours() + ":" + new Date().getMinutes(),
      id: "",
      type: "ppw",
      toId: "",
    };
    if (opportunityId) {

      const params = {
        msg,
        myOpportunityId,
        userId: localStorage.getItem("userId"), opportunityId
      };

      await this.post("message/inviteChat", params, async (response) => {
        const data = response;
        if (data.status !== "success" || data.user_id === null) {
          // this.appGlobalService.showToast('邀约成功', 2000, 'middle');
        } else {
          item.toId = data.user_id;
          item.id = data.user_id + "-" + localStorage.getItem("userId");
          callback(item);
        }
      }, (error) => {
        // 接口报错不处理
        console.log("msg-----> error:" + JSON.stringify(error));
      });
    }
    // 铺小旺处理客户id
    // else if (customerId) {
    //   // 铺小旺直接处理客户id
    //   item.type = "pxw";
    //   await this.get("message/customer/" + customerId, async (customerResp) => {
    //     if (customerResp.status !== "success") {
    //       
    //       this.appGlobalService.showToast(customerResp["msg"], 3000, "middle");
    //       return;
    //     } else {
    //       item.toId = customerResp.user_id;
    //       item.id = customerResp.user_id + "-" + localStorage.getItem("userId");
    //       callback(item);
    //     }
    //   });
    // }
  }

  /** 换取临时号码拨打电话 */
  changeCallNumber(telN) {


    if (!telN) {
      return;
    }
    if (this.appGlobalService.clientType === "pxw") {
      this.post(
        "element/prepareHideTel",
        { tela: localStorage.getItem("loginAccount"), telb: telN },
        (res) => {
          console.log(JSON.stringify(res));
          // {"code":0,"message":"SUCCESS","telX":"13240396682"}
          if (res.code === 0 && res.telX) {
            this.callNumber(res.telX);
          } else {
            if (res.message && res.message.length > 0) {
              this.appGlobalService.showToast(res.message, 1500, "middle");
            } else {
              this.appGlobalService.showToast("操作失败", 1500, "middle");
            }
          }
        }
      );
    } else {
      this.callNumber(telN);
    }
  }

  // 2024.01.25 增加安卓开启拨打号码权限
  callNumber(telN) {

    // 安卓app 
    if (localStorage.getItem('client') === 'APP' && localStorage.getItem('platform') === 'android') {

      if (localStorage.getItem('enableCallNumberPermission') === 'true') {
        document.location.href = "tel:" + telN;
      } else {
        this.callNumberPermissionAlertConfirm(telN);
      }
    } else {
      document.location.href = "tel:" + telN;
    }
  }

  async callNumberPermissionAlertConfirm(telN) {
    const alert = await this.alertController.create({
      header: this.appGlobalService.callNumberTipsHeader,
      message: this.appGlobalService.callNumberTipsContent,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "去开启",
          handler: () => {
            localStorage.setItem('enableCallNumberPermission', 'true');
            document.location.href = "tel:" + telN;
          }
        }
      ]
    });

    await alert.present();
  }

  bindWeChatLoginCode(callBack?) {
    const that = this;
    let path = 'element/wechat/auth/';
    if (this.appGlobalService.clientType === 'ppw') {
      path = 'element/wechat/auth/';
    } else {
      path = 'element/wechat/fwAuth/';
    }

    this.http.get(this.bathUrl + path + localStorage.getItem('sessionId') + '/' + this.appGlobalService.wxLoginCode, { responseType: 'text' }).subscribe(
      (data) => {
        if (data === 'success') {
          localStorage.setItem(localStorage.getItem('sessionId'),"bindWeChatLoginCode")
          // that.appGlobalService.showToast('binde success', 1500, 'middle');
          this.appGlobalService.wxLoginCode = '';
          callBack(localStorage.getItem('sessionId'));
        } else {
          ++that.retry;
          if (that.retry < 3) {
            that.bindWeChatLoginCode(callBack);
          } else {
            // that.appGlobalService.showToast('binde fail', 1500, 'middle');
          }
        }
      },
      (error) => {
        // that.appGlobalService.showToast('binde error', 1500, 'middle');
        ++that.retry;
        if (that.retry < 3) {
          that.bindWeChatLoginCode(callBack);
        } else {
          console.log('wechat code binde fail');
          // that.appGlobalService.showToast('binde fail', 1500, 'middle');
        }
      }
    );
    // }, err => {

    // })
  }
}
